import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000, // request timeout
});
// request interceptor
service.interceptors.request.use(
  (config) => {
    // 若是登陆请求，直接放行
    const url = config.url;
    if (url.indexOf("oauth/token") > -1) {
      config.headers["Content-Type"] = "application/x-www-form-urlencoded";
      return config;
    } else {
      config.headers["Content-Type"] = "application/json";
    }
    // if (getToken()) {
    //   config.headers["Authorization"] = "Bearer " + getToken();
    // }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    if (
      response.data &&
      response.data.completeCode &&
      response.data.completeCode === 1
    ) {
      // 登陆成功的数据体不一样
      if (response.data.access_token) {
        return Promise.resolve(response.data);
      }
      // 正常响应，且响应值为1，返回数据
      return Promise.resolve(response.data.data);
    } else {
      Message({
        message: response.data.reasonMessage,
        type: "error",
        duration: 5 * 1000,
      });
    }

    // return Promise.reject(response.data);
  },
  (error) => {
    // status 校验不通过
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    // 若是登陆校验失败，则退出到登陆页面
    if (
      error.response.data &&
      error.response.data.reasonCode &&
      error.response.data.reasonCode === "10001"
    ) {
      // 没有token跳转到登陆页面
      store.dispatch("LogOut").then(() => {
        // location.reload() // 为了重新实例化vue-router对象 避免bug
        router.push(`/login`);
      });
    }
    return Promise.reject(error);
  }
);

export default service;
